import CryptoJS from 'crypto-js'

const createNonceStr = () => {
  return Math.random().toString(36).substr(2, 15)
}

const createTimestamp = () => {
  return parseInt(new Date().getTime() / 1000) + ''
}

const raw = (args) => {
  var keys = Object.keys(args)
  keys = keys.sort()
  var newArgs = {}
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key]
  })

  var string = ''
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k]
  }
  string = string.substr(1)
  return string
}

/**
 * 获取解密之后的字符串
 * @param {*} encrypted 需要解密的字符串
 * @param {*} key 秘钥
 * @param {*} iv 偏移向量
 */
const wechatSignature = (jsapiTicket, url) => {
  if (!url && typeof jsapiTicket === 'object') {
    var ss = raw(jsapiTicket)
    jsapiTicket.signature = CryptoJS.SHA1(ss).toString()
    return jsapiTicket
  }
  var ret = {
    jsapi_ticket: jsapiTicket,
    nonceStr: createNonceStr(),
    timestamp: createTimestamp(),
    url: url
  }
  var string = raw(ret)
  ret.signature = CryptoJS.SHA1(string).toString()
  return ret
}

/**
 * @synopsis 签名算法
 *
 * @param jsapi_ticket 用于签名的 jsapi_ticket
 * @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
 *
 * @returns
 */
export default wechatSignature
